package caculate.linkedList;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-10 23:43
 **/
public class ReverseBetween {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null)))));
//        ListNode listNode = new ListNode(3, new ListNode(5, null));
        ListNode listNode1 = reverseBetween(listNode, 2, 4);
        System.out.println();
    }


    public static ListNode reverseBetween(ListNode head, int left, int right) {
        int index = 0;

        ListNode dummyLink = head;

        ListNode curr = dummyLink;
        ListNode lNode = null;
        ListNode newLink = null;
        ListNode newLinkLast = null;
        while (curr != null) {
            index++;
            ListNode next = curr.next;
            // 记录左边界
            if (index == left - 1) {
                lNode = curr;
            // 中间部分用于创建倒置链表
            } else if (index >= left && index <= right) {
                curr.next = newLink;
                if (newLink == null) {
                    newLinkLast = curr;
                }
                newLink = curr;
            } else if (index > right && newLinkLast != null) {
            // 后面如果还有就拼到新链表后面
                newLinkLast.next = curr;
                newLinkLast = curr;
            }
            curr = next;
        }

        // 最后如果把新链表拼到左边界后
        if (lNode != null) {
            lNode.next = newLink;
            return dummyLink;
        }

        return dummyLink;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
